package de.hijacksoft.isledesktopsync;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;

public class Toast extends JPanel implements Runnable {
    
    private boolean canRun = false;
    private Thread th;
    private String text = "";
    private long time;
    
    private Color color_bg = new Color(0.3f, 0.3f, 0.3f, 0);
    private Color color_border = new Color(0.7f, 0.7f, 0.7f, 0);
    
    private int alpha = 0;
    
    private JPanel parent;
    
    private static Toast instance;
    
    public Toast(JPanel bg){
        super();
        parent = bg;
        this.setBackground(new Color(0,0,0,0));
        instance = this;
    }
    
    public static Toast makeText(String text, long time){
        instance.text = text;
        instance.time = time;        
        return instance;
    }
    
    @Override
    public void show(){
        showText(text, time);
    }
    
    private void showText(String text, long time){
        this.text = text;
        this.time = time;
        th = new Thread(this);
        canRun = true;
        th.start();
    }
    
    private int inc = 0;
    
    @Override 
    public void paintComponent(Graphics g) {         

         super.paintComponent(g);
         parent.repaint();
         
         g.setFont(new Font("Droid Sans", Font.BOLD, 12));
         double textwidth = g.getFontMetrics(g.getFont()).getStringBounds(text, g).getWidth();

         color_bg = new Color(color_bg.getRed(), color_bg.getGreen(), color_bg.getBlue(), alpha);         
         color_border = new Color(color_border.getRed(), color_border.getGreen(), color_border.getBlue(), alpha);  
         
         g.setColor(color_bg);
         g.fillRoundRect(5, 5, 300, 30, 15, 15);
         
         g.setColor(color_border);
         g.drawRoundRect(5, 5, 300, 30, 15, 15);
         
         g.setColor(new Color(255, 255, 255, color_bg.getAlpha()));

         g.drawString(text, 150-(int)(textwidth/2) , 25);
    }

    @Override
    public void run(){
        if(canRun){
            canRun = false;
            
            try {
            
            while(alpha < 255){
                alpha++;
                repaint();
                th.sleep(1);
            }
            
            th.sleep(time);

            while(alpha > 0){
                alpha--;
                repaint();
                th.sleep(1);
            }
            
            } catch (InterruptedException ex) {
                Logger.getLogger(Toast.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }
    
}